package com.open.chat.server.listener;

import org.jim.core.ImChannelContext;
import org.jim.core.ImSessionContext;
import org.jim.core.exception.ImException;
import org.jim.core.packets.Group;
import org.jim.core.packets.JoinGroupNotifyRespBody;
import org.jim.core.packets.User;
import org.jim.core.packets.UserStatusType;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.listener.AbstractImGroupListener;
import org.jim.server.protocol.ProtocolManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 群组绑定监听器
 * @author WChao 
 * 2017年5月13日 下午10:38:36
 */
public class ImGroupListener extends AbstractImGroupListener {

	private  static Logger logger = LoggerFactory.getLogger(ImGroupListener.class);

	@Override
	public void doAfterBind(ImChannelContext imChannelContext, Group group) throws ImException {
		logger.info("群组:{},绑定成功!", JsonKit.toJSONString(group));
		
		//获取当前登录的用户
//		ImSessionContext imSessionContext = imChannelContext.getSessionContext();
//		User clientUser = imSessionContext.getImClientNode().getUser();
//		//告诉群里的人说：当前用户已经登录
//		SystemNotify.notifyGroup(Command.COMMAND_JOIN_GROUP_NOTIFY_RESP, 
//					group.getGroupId(), group.getName(), 
//					String.format("%s已进入房间", clientUser.getNick()));
		
	}

	/**
	 * @param imChannelContext
	 * @param group
	 * @throws Exception
	 * @author: WChao
	 */
	@Override
	public void doAfterUnbind(ImChannelContext imChannelContext, Group group) throws ImException {
		//退出房间通知  Command.COMMAND_EXIT_GROUP_NOTIFY_RESP
		
//		User clientUser = imChannelContext.getSessionContext().getImClientNode().getUser();
//		if(clientUser == null) {
//			return;
//		}
//		//告诉群里的人说：当前用户已经退群
//		SystemNotify.notifyGroup(Command.COMMAND_EXIT_GROUP_NOTIFY_RESP, 
//					group.getGroupId(), group.getName(), 
//					String.format("%s已退群", clientUser.getNick()));
		
	}

	/**
	 * 发送进房间通知;
	 * @param group 群组对象
	 * @param imChannelContext
	 */
	@Deprecated
	public void joinGroupNotify(Group group, ImChannelContext imChannelContext)throws ImException{
		ImSessionContext imSessionContext = imChannelContext.getSessionContext();
		User clientUser = imSessionContext.getImClientNode().getUser();
		User notifyUser = User.newBuilder().userId(clientUser.getUserId()).nick(clientUser.getNick()).status(UserStatusType.ONLINE.getStatus()).build();
		String groupId = group.getGroupId();
		//发进房间通知  COMMAND_JOIN_GROUP_NOTIFY_RESP
		JoinGroupNotifyRespBody joinGroupNotifyRespBody = JoinGroupNotifyRespBody.success();
		joinGroupNotifyRespBody.setGroup(groupId).setUser(notifyUser);
		JimServerAPI.sendToGroup(groupId, ProtocolManager.Converter.respPacket(joinGroupNotifyRespBody,imChannelContext));
	}
	
	

}
